<template>
	<view>
		<u-notify ref="uNotify"></u-notify>
		<u-collapse ref='coll' :value="['1','2']">
			<u-collapse-item name="1" title="基本信息" icon="https://project.gxrunxiang.com/cdn/my.png">
				<u-form labelPosition='top' name="basic" layout="horizontal" :rules="rules" :model="buildDetail"
			:labelCol="{span:7}" :wrapperCol="{span: 13, offset: 0}" ref="uForm" label-width="auto">
					<u-form-item label="项目"  @click="openpage" :required="true" >
						<u-input v-model="projName" disabled/>
					</u-form-item>
					<u-form-item label="项目Id" v-if="false"   prop="ProjId">
						<u-input v-model="buildDetail.ProjId"/>
					</u-form-item>
					<u-form-item label="工程名称"  :required="true"  prop="Name">
						<u-input v-model="buildDetail.Name"  @change="getno"/>
					</u-form-item>
					<u-form-item label="工程编号"   :required="true"  prop="No">
						<u-input v-model="buildDetail.No" />
					</u-form-item>
					<u-form-item label="建设单位" :required="true"  prop="FirstUnit">
						<u-input v-model="buildDetail.FirstUnit" />
					</u-form-item>
					<u-form-item label="地市" @click="showCity = true;" :required="true"  prop="City">
						<u--input v-model="buildDetail.City" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="施工单位" @click="showSecondUnit = true;" :required="true"  prop="SecondUnit">
						<u--input v-model="buildDetail.SecondUnit" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="工程性质" @click="showBuildProperty = true; ">
						<u--input v-model="buildDetail.BuildProperty" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="区域">
						<u-input v-model="buildDetail.Zone" disabled/>
					</u-form-item>
					<!-- <u-form-item label="县"><u-input v-model="buildDetail.Town" /></u-form-item> -->
					<u-form-item label="工程地址">
						<span slot="label">
							<span style="display: flex;">工程地址 
								<u-icon name="question-circle" color="#2979ff" size="18"  @click.native.stop="showToast"></u-icon>
							</span>
						</span>
						<u-input v-model="buildDetail.Addr" />
					</u-form-item>
					<u-form-item label="开工时间" @click="showStart = true; "　:required="true"  prop="StartTime">
						<u--input　v-model="buildDetail.StartTime" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="预计完工时间" @click="showEnd = true;">
						<u--input　v-model="buildDetail.PlanEndTime" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="工程工期(天)">
						<u-number-box :min="0" integer v-model="buildDetail.LimitTime" />
					</u-form-item>
					<u-form-item label="工程类别" @click="showBuildType = true; ">
						<u--input v-model="buildDetail.BuildType" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="网络类型" @click="showNetworkType = true;" v-if="isProtect" :required="true"  prop="NetworkType">
						<u--input v-model="buildDetail.NetworkType" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="市级项目部" v-if="isProtect" :required="true"  prop="CityDept">
						<u--input v-model="buildDetail.CityDept"/>
					</u-form-item>
					<u-form-item label="县级项目部" v-if="isProtect" :required="true"  prop="CountyDept">
						<u--input v-model="buildDetail.CountyDept"/>
					</u-form-item>
					<u-form-item label="维护类型" @click="showMaintenance = true;" v-if="isProtect" :required="true"  prop="MaintenanceType">
						<u--input v-model="buildDetail.MaintenanceType" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="维护工单编号" v-if="isProtect" :required="true"  prop="MaintenanceNo">
						<u--input v-model="buildDetail.MaintenanceNo" @blur="handleBlur"/>
					</u-form-item>
					<u-form-item label="维护方式" @click="showMaintenanceMethod = true;" v-if="isProtect" :required="true"  prop="MaintenanceMethod">
						<u--input v-model="buildDetail.MaintenanceMethod" disabledColor="#ffffff" disabled />
					</u-form-item>
					<u-form-item label="施工内容">
						<u--textarea v-model="buildDetail.BuildContent" placeholder="请输入内容" height="180" maxlength="300"></u--textarea>
					</u-form-item>
					<u-form-item label="影响范围" :required="true"  @click="showAddress = true" v-if="isProtect"><u-input disabledColor="#ffffff" disabled /></u-form-item>
					<u-button @click="toChoose" v-if="isProtect">添加影响范围</u-button>
					<u--text v-for="item in standardAddrList" margin="0 0 8px 0" type="info" :text="item.addr" @click='delAddr(item)' v-if="isProtect"></u--text>
					</u--text>
					<u-popup :show="showAddress" title="请选择影响范围" @close="showAddress = false">
						<u-search placeholder="多个关键词请用空格隔开" v-model="keyword" @custom="selectAddr" @search="selectAddr"></u-search>
						<u-list height='460px' @scrolltolower="scrolltolower">
							<u-list-item v-for="(item, index) in addrlist" :key="index">
								<u-cell :title='item.FullName' @click="changeAddr(item.FullName,item.AddrCode)">
								</u-cell>
							</u-list-item>
							<u-loadmore :status="addrStatus" v-if="addrLoading" />
						</u-list>
					</u-popup>
					<u-form-item label="工程负责人">
						<u--input v-model="buildDetail.BuildManager"/>
					</u-form-item>
					<u-form-item label="施工方负责人">
						<u--input v-model="buildDetail.ProjManager"/>
					</u-form-item>
					<u-form-item label="施工人员">
						<u--input v-model="buildDetail.Safer"/>
					</u-form-item>
			</u-form>
			</u-collapse-item>
			<u-collapse-item name="1" title="现场照片" icon="https://project.gxrunxiang.com/cdn/image.png">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					itype='现场照片' :sizeType='["compressed"]' :maxCount="10"></u-upload>
			</u-collapse-item>
		</u-collapse>
		<u-action-sheet :show="showSecondUnit" :actions="dicOptions" title="请选择施工单位" 											@close="showSecondUnit = false" @select="secondUnitSelect">
		</u-action-sheet>
		<u-action-sheet :show="showCity" :actions="dicCity" title="请选择地市" @close="showCity = false"
			@select="citySelect">
		</u-action-sheet>
		<u-action-sheet :show="showBuildProperty" :actions="dicBuildProperty" title="请选择工程性质" 									@close="showBuildProperty = false" @select="buildPropertySelect">
		</u-action-sheet>
		<u-action-sheet :show="showBuildType" :actions="dicBuildType" title="请选择工程类别" 											@close="showBuildType = false" @select="buildTypeSelect">
		</u-action-sheet>
		<u-action-sheet :show="showNetworkType" :actions="dicNetworkType" title="请选择网络类型" 										@close="showNetworkType = false" @select="networkTypeSelect">
		</u-action-sheet>
		<u-action-sheet :show="showMaintenance" :actions="dicMaintenance" title="请选择维护类型" 										@close="showMaintenance = false" @select="maintenanceSelect">
		</u-action-sheet>
		<u-action-sheet :show="showMaintenanceMethod" :actions="dicMaintenanceMethod" title="请选择维护方式" 							@close="showMaintenanceMethod = false" @select="maintenanceMethodSelect">
		</u-action-sheet>
		<u-datetime-picker
		  :show="showStart"
		  @cancel="showStart = false"
		  @confirm="changeStartTime" :closeOnClickOverlay="true" @close="showStart = false"
		  mode="date"
		  v-model="value1"
		  :minDate="1704038400000"
		></u-datetime-picker>
		<u-datetime-picker
		  :show="showEnd"
		  @cancel="showEnd = false"
		  @confirm="changeEndTime" :closeOnClickOverlay="true" @close="showEnd = false"
		  mode="date"
		  v-model="value2"
		  :minDate="1704038400000"
		></u-datetime-picker>
		<u-button @click="submit">提交</u-button>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>
<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		mapGetters
	} from 'vuex'

	import {
		addfault,
		GetListByParent,
		GetFGSname,
		getno,
		city,
		getaddrslist,
		addbuild,
		getorderlist
	} from '@/common/api.js'
	export default {
		data() {
			return {
				itypelist: {
					"1": "现场照片",
				},
				buildDetail: {
					No:"",
					LimitTime: 0,
					CityDept: "",
					CountyDept: "",
					AddrCodes: "",
					StandardAddress: "",
				},
				fileList1: [],
				fileList2: [],
				token: "",
				dicOptions: [],
				dicCity: [],
				dicBuildProperty: [],
				dicBuildType: [],
				dicNetworkType: [],
				dicMaintenance:[{
				    name: '大修整治',
				},{
				    name: '日常维护'
				}],
				dicMaintenanceMethod:[{
				    name: '自维'
				},{
				    name: '外派',
				}],
				showSecondUnit: false,
				showCity: false,
				showBuildProperty: false,
				showBuildType: false,
				showStart: false,
				showEnd: false,
				showNetworkType: false,
				showMaintenance: false,
				showMaintenanceMethod:false,
				user: {},
				projName: "",
				FirstUnitName: "",
				city: [],
				value1: Number(new Date()), //当前时间
				value2: Number(new Date()),
				isProtect: false, //项目是否维护
				cityDept: "", //市级项目部
				countyDept: "", //县级项目部
				standardAddrList: [], //影响范围的列表
				keyword: "", // 查询列表的关键词
				showAddress: false,
				addrlist:{},
				pageIndex: 1, //当前页数
				pageSize: 20, //页数大小
				totalPage: "", //总页数
				total: 0, //数据总数
				addrStatus: 'loadmore', //加载状态
				addrLoading: false,
				errorNotify: {
					message: '请选择标准地址!',
					type: 'error',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 2000,
					safeAreaInsetTop: false
				},
				projNotify: {
					message: '请选择项目!',
					type: 'error',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 2000,
					safeAreaInsetTop: false
				},
 				rules: {
					'Name': {
						type: 'string',
						required: true,
						message: '请填写名称',
						trigger: ['blur', 'change']
					},
					'No' : {
						type: 'string',
						required: true,
						message: '请填写编号',
						trigger: ['blur', 'change']
					},
					'FirstUnit' : {
						type: 'string',
						required: true,
						message: '请填写建设单位',
						trigger: ['blur', 'change']
					},
					'City' : {
						type: 'string',
						required: true,
						message: '请填写地市',
						trigger: ['blur', 'change']
					},
					'SecondUnit' : {
						type: 'string',
						required: true,
						message: '请填写施工单位',
						trigger: ['blur', 'change']
					},
					'StartTime' : {
						type: 'string',
						required: true,
						message: '请填写开工时间',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		onLoad() {
			GetListByParent("协作单位", this.dicOptions)
			GetListByParent("广西地市", this.dicCity)
			GetListByParent("工程性质", this.dicBuildProperty)
			GetListByParent("工程类别", this.dicBuildType)
			GetListByParent("网络类型", this.dicNetworkType)
			this.token = uni.getStorageSync("$token")
			this.city = city
		},
		onShow() {
			let user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.user = user
			if(!this.FirstUnitName){
				GetFGSname(this.user.DeptId).then(res =>{
					if(res.length)
					this.FirstUnitName = res
					this.buildDetail.FirstUnit =  '广西润象信息网络工程有限公司' + this.FirstUnitName
				})
			}
			if(this.user.Dept.FullName.split('/')[2])
			    this.cityDept = this.user.Dept.FullName.split('/')[2]
			if(this.user.Dept.FullName.split('/')[3]){
			    this.countyDept = this.user.Dept.FullName.split('/')[3]
			}else if(this.user.Dept.FullName.split('/')[2]){
			    this.countyDept = this.user.Dept.FullName.split('/')[2]
			}
			this.standardAddrList = []
			for(let i = 0;i<getApp().globalData.buildAddrId.length;i++){
				this.standardAddrList[i] = {
					code: getApp().globalData.buildAddrId[i],
					addr: getApp().globalData.buildAddrName[i]
				}
			}
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			secondUnitSelect(e) {
				this.buildDetail.SecondUnit = e.name
			},
			citySelect(e) {
				this.buildDetail.City = e.name
				this.setzone()
			},
			buildPropertySelect(e){
				this.buildDetail.BuildProperty = e.name
			},
			buildTypeSelect(e){
				this.buildDetail.BuildType = e.name
			},
			networkTypeSelect(e){
				this.buildDetail.NetworkType = e.name
			},
			maintenanceSelect(e){
				this.buildDetail.MaintenanceType = e.name
			},
			maintenanceMethodSelect(e){
				this.buildDetail.MaintenanceMethod = e.name
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {				console.log(event.name);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, itype) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.buildDetail.Id||this.user.Id}&type=${itype}`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			submit() {
					if(this.standardAddrList.length == 0 && this.isProtect){
						this.$refs.uNotify.show(this.errorNotify)
						return;
					}
					if(!this.buildDetail.ProjId){
						this.$refs.uNotify.show(this.projNotify)
						return;
					}
					this.$refs.uForm.validate().then(res => {
							this.standardAddrList.forEach(e=>{
								this.buildDetail.AddrCodes = this.buildDetail.AddrCodes + ',' + e.code
								this.buildDetail.StandardAddress = this.buildDetail.StandardAddress + ',' + e.addr
							})
							getApp().globalData.buildAddrId = []
							getApp().globalData.buildAddrName = []
							addbuild(this.buildDetail).then((res) => {
								if (res === true) {
									uni.navigateBack()
								}
							})
						}).catch(errors => {
							console.log(errors);
							uni.$u.toast('请填写必填参数！')
						})	
			},
			openpage(e)
			{ 
				uni.navigateTo({
					url: "c_projselect"
				})
			},
			getProj(Id,Name,Usefor){
				this.projName = Name
				this.buildDetail.ProjId = Id
				if(Usefor == '维护'){
					this.isProtect = true
					this.buildDetail.CityDept = this.cityDept
					this.buildDetail.CountyDept = this.countyDept
					this.rules = {
						'Name': {
							type: 'string',
							required: true,
							message: '请填写名称',
							trigger: ['blur', 'change']
						},
						'No' : {
							type: 'string',
							required: true,
							message: '请填写编号',
							trigger: ['blur', 'change']
						},
						'FirstUnit' : {
						type: 'string',
						required: true,
						message: '请填写建设单位',
						trigger: ['blur', 'change']
						},
						'City' : {
							type: 'string',
							required: true,
							message: '请填写地市',
							trigger: ['blur', 'change']
						},
						'SecondUnit' : {
							type: 'string',
							required: true,
							message: '请填写施工单位',
							trigger: ['blur', 'change']
						},
						'StartTime' : {
							type: 'string',
							required: true,
							message: '请填写开工时间',
							trigger: ['blur', 'change']
						},
						'NetworkType' : {
							type: 'string',
							required: true,
							message: '请填写网络类型',
							trigger: ['blur', 'change']
						},
						'CityDept' : {
							type: 'string',
							required: true,
							message: '请填写市级项目部',
							trigger: ['blur', 'change']
						},
						'CountyDept' : {
							type: 'string',
							required: true,
							message: '请填写县级项目部',
							trigger: ['blur', 'change']
						},
						'MaintenanceType' : {
							type: 'string',
							required: true,
							message: '请填写维护类型',
							trigger: ['blur', 'change']
						},
						'MaintenanceNo' : {
							type: 'string',
							required: true,
							message: '请填写维护工单编号',
							trigger: ['blur', 'change']
						},
						'MaintenanceMethod' : {
							type: 'string',
							required: true,
							message: '请填写维护方式',
							trigger: ['blur', 'change']
						},
					}
					this.$refs.uForm.setRules(this.rules)
				}else{
					this.isProtect = false
					this.rules = {
						'Name': {
							type: 'string',
							required: true,
							message: '请填写名称',
							trigger: ['blur', 'change']
						},
						'No' : {
							type: 'string',
							required: true,
							message: '请填写编号',
							trigger: ['blur', 'change']
						},
						'FirstUnit' : {
						type: 'string',
						required: true,
						message: '请填写建设单位',
						trigger: ['blur', 'change']
						},
						'City' : {
							type: 'string',
							required: true,
							message: '请填写地市',
							trigger: ['blur', 'change']
						},
						'SecondUnit' : {
							type: 'string',
							required: true,
							message: '请填写施工单位',
							trigger: ['blur', 'change']
						},
						'StartTime' : {
							type: 'string',
							required: true,
							message: '请填写开工时间',
							trigger: ['blur', 'change']
						},
					}
					this.$refs.uForm.setRules(this.rules)
					this.buildDetail.CityDept = ""
					this.buildDetail.CountyDept = ""
				}
				if(this.buildDetail.Name.length != 0){
					this.getno()
				}
			},
			getno() {
			    if (!this.buildDetail.ProjId)
			        return
			    getno(this.buildDetail).then(res => {
			        this.buildDetail.No = res
			    })
			},
			setzone() {
			    let city = this.buildDetail.City.replace("市", "").replace("县", "").replace("镇", "")
			    var c = this.city.find(e => e.name.replace("市", "").replace("县", "") == city || e.districtAndCounty.find(i => i.replace("市", "").replace("县", "").replace("镇", "") == city) != null)
			    this.buildDetail.Zone = c.code
			},
			showToast(){
				this.$refs.uToast.show({
					message: '请按照 XX市XX县/区XX镇XX村屯XX道路XX门牌号等 格式填写',
					type: 'default',
					duration: 3000
				})
			},
			changeStartTime(e){
				const timeFormat = uni.$u.timeFormat
				this.buildDetail.StartTime = timeFormat(e.value, 'yyyy-mm-dd')
				if(this.buildDetail.StartTime && this.buildDetail.PlanEndTime){
				    this.buildDetail.LimitTime = Math.ceil((this.buildDetail.PlanEndTime - this.buildDetail.StartTime) / (1000 * 3600 * 24))}
				this.showStart = false
			},
			changeEndTime(e){
				const timeFormat = uni.$u.timeFormat
				this.buildDetail.PlanEndTime = timeFormat(e.value, 'yyyy-mm-dd')
				if(this.buildDetail.StartTime!=undefined && this.buildDetail.PlanEndTime.length!=undefined){
				    this.buildDetail.LimitTime = Math.ceil((new Date(this.buildDetail.PlanEndTime).getTime() - new Date(this.buildDetail.StartTime).getTime()) / (1000 * 3600 * 24))}
				this.showEnd = false
			},
			toChoose(){
				uni.navigateTo({
					url: "buildaddr?level=0&backto=1"
				})
			},
			delAddr(e){
				var idList = getApp().globalData.buildAddrId
				var nameList = getApp().globalData.buildAddrName
				var idIndex = idList.findIndex(item => item === e.code);
				var nameIndex = nameList.findIndex(item => item === e.addr);
				getApp().globalData.buildAddrId = idList.filter((_, i) => i !== idIndex)
				getApp().globalData.buildAddrName = nameList.filter((_, i) => i !== nameIndex)
				this.standardAddrList = []
				for(let i = 0;i<getApp().globalData.buildAddrId.length;i++){
					this.standardAddrList[i] = {
						code: getApp().globalData.buildAddrId[i],
						addr: getApp().globalData.buildAddrName[i]
					}
				}
			},
			selectAddr(){
				this.addrlist = [];
				this.pageIndex = 1;
				this.addrLoading = true
				this.getaddrlist()
			},
			async getaddrlist(){
				let para = {}
				para.OrderBys = ['Id desc'];
				para.pageSize = this.pageSize;
				para.pageIndex = this.pageIndex;
				para.Parameters = [];
				var selcets = this.keyword.split(' ');
				for(let i = 0;i < selcets.length;i++){
					if(selcets[i].length > 0)
					para.Parameters.push({
					   	FieldName: "FullName",
					   	ConditionalType: "Like",
					   	FieldValue: selcets[i]
					   })
				}
				await getaddrslist(para).then(res => {
					this.addrlist.push(...res.data)
					this.total = res.count
					this.totalPage = Math.ceil(this.total / this.pageSize)
				})
				if (this.addrlist.length < this.pageSize) {
					this.addrLoading = false; //如果数据列表小于当前页数，就让加载标签消失
					this.addrStatus = 'nomore';
				}else {
					this.addrStatus = 'loadmore';
				}
			},
			scrolltolower() {
				// 如果当前页数大于等于总页数，状态修改为没有更多了，不再继续往下执行代码
				if (this.pageIndex >= this.totalPage) {
					this.addrStatus = 'nomore';
					return;
				};
				this.addrStatus = 'loading'; //状态改为加载中
				this.pageIndex = ++this.pageIndex; //页面新增一页
				this.getaddrlist(); //修改页数后，重新获取数据
			},
			changeAddr(e,c){
				this.showAddress = false;
				const toggleArrayValue = (arr, value) => {
				  // 检查是否存在（使用严格相等判断）
				  const index = arr.findIndex(item => item === value);
				  // 存在则删除，不存在则添加
				  return index === -1 
					? [...arr, value] 
					: arr.filter((_, i) => i !== index);
				};
				getApp().globalData.buildAddrId = toggleArrayValue(getApp().globalData.buildAddrId,c)
				getApp().globalData.buildAddrName = toggleArrayValue(getApp().globalData.buildAddrName,e)
				for(let i = 0;i<getApp().globalData.buildAddrId.length;i++){
					this.standardAddrList[i] = {
						code: getApp().globalData.buildAddrId[i],
						addr: getApp().globalData.buildAddrName[i]
					}
				}
			},
			handleBlur(e){
				if(e){
				    let para = {
				        Parameters: [{
							FieldName: "No",
							ConditionalType: "Equal",
							FieldValue: e
						}],
						OrderBys: ['Id desc'],
						pageSize : 1,
						pageIndex : 1
				    }
				    getorderlist(para).then(res=>{
				        if(res.count == 1){
				            var addrCodes = res.data[0].AddrCodes.split(',')
				            var standardAddress = res.data[0].StandardAddress.split(',')
							getApp().globalData.buildAddrId = []
							getApp().globalData.buildAddrName = []
				            for(var i = 1; i < addrCodes.length; i++) {
								getApp().globalData.buildAddrId.push(addrCodes[i])
								getApp().globalData.buildAddrName.push(standardAddress[i])
				            }
							this.standardAddrList = []
							for(let i = 0;i<getApp().globalData.buildAddrId.length;i++){
								this.standardAddrList[i] = {
									code: getApp().globalData.buildAddrId[i],
									addr: getApp().globalData.buildAddrName[i]
								}
							}
				        }
				    })
				}
			}
		}
	}
</script>